package play

import (
	"encoding/json"
	"errors"
	"github.com/gorilla/websocket"
	"log"
)

type C2SPlay struct {
	Type     string   `json:"type"`
	Position Position `json:"position"`
}

var curr = 1
var chessboard = make([][]int, 15)

func init() {
	for i := 0; i < 15; i++ {
		chessboard[i] = make([]int, 15)
	}
}

func Play(clients map[*websocket.Conn]*User, conn *websocket.Conn, data string) (t string, re interface{}, err error) {
	var user = clients[conn]
	t = "play"
	if user.Type == 3 {
		return t, nil, errors.New("没有选择棋子")
	}
	if curr != user.Type {
		return t, nil, errors.New("没有轮到你落子")
	}
	log.Println(data)
	var p C2SPlay
	err = json.Unmarshal([]byte(data), &p)
	if err != nil {
		return t, nil, err
	}
	chessboard[p.Position.X][p.Position.Y] = curr
	if CheckForWin(p.Position, curr, chessboard) {
		t = "win"
		re = p
		claer()
		return
	}
	curr = 3 - curr
	re = p
	return
}

// CheckForWin 检测胜负
func CheckForWin(pos Position, val int, c [][]int) bool {
	// 判断当前落子位置纵向是否满足胜利条件
	count := 0
	for i := 0; i < 15; i++ {
		if c[pos.X][i] == val {
			count++
			if count >= 5 {
				return true
			}
		} else {
			count = 0
		}
	}

	// 判断当前落子位置纵向是否满足胜利条件
	count = 0
	for i := 0; i < 15; i++ {
		if c[i][pos.Y] == val {
			count++
			if count >= 5 {
				return true
			}
		} else {
			count = 0
		}
	}

	// 判断当前落子位置下斜行是否满足胜利条件
	decline := make([]int, 5)
	x := pos.X + 1
	y := pos.Y + 1
	for x > 0 && y > 0 {
		x--
		y--
	}
	for x < 15 && y < 15 {
		decline = append(decline, c[x][y])
		x++
		y++
	}
	for i, l := 0, len(decline); i < l; i++ {
		if decline[i] == val {
			count++
			if count >= 5 {
				return true
			}
		} else {
			count = 0
		}
	}

	// 判断当前落子位置上斜行是否满足胜利条件
	overthrust := make([]int, 5)
	x = pos.X
	y = pos.Y
	for x > 0 && y < 15 {
		x--
		y++
	}
	for x < 15 && y > 0 {
		overthrust = append(overthrust, c[x][y])
		x++
		y--
	}
	for i, l := 0, len(overthrust); i < l; i++ {
		if overthrust[i] == val {
			count++
			if count >= 5 {
				return true
			}
		} else {
			count = 0
		}
	}
	return false
}
func claer()  {
	for i := 0; i < 15; i++ {
		for j := 0; j < 15; j++ {
			chessboard[i][j]=0
		}
	}
}